package org.teamh.gui.ingame;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.teamh.connection.handler.ConnectionHandler;
import org.teamh.connection.json.NOOP;
import org.teamh.connection.json.command.JsonSender;
import org.teamh.gui.GUI;
import org.teamh.gui.engine.ogg.BackgroundMusic;
import org.teamh.gui.ingame.chat.ChatManager;
import org.teamh.gui.ingame.effects.EffectManager;
import org.teamh.gui.lobby.ChatListBoxViewConverter;
import org.teamh.logic.datamodel.CreepDescription;
import org.teamh.logic.datamodel.Tile;
import org.teamh.logic.datamodel.Tower;
import org.teamh.logic.datamodel.TowerDescription;
import org.teamh.logic.datamodel.User;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.Button;
import de.lessvoid.nifty.controls.DropDown;
import de.lessvoid.nifty.controls.DropDownSelectionChangedEvent;
import de.lessvoid.nifty.controls.Label;
import de.lessvoid.nifty.controls.ListBox;
import de.lessvoid.nifty.controls.TextField;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.events.NiftyMousePrimaryClickedEvent;
import de.lessvoid.nifty.elements.render.ImageRenderer;
import de.lessvoid.nifty.elements.render.PanelRenderer;
import de.lessvoid.nifty.elements.render.TextRenderer;
import de.lessvoid.nifty.elements.tools.TextBreak;
import de.lessvoid.nifty.input.NiftyInputEvent;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.screen.KeyInputHandler;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import de.lessvoid.nifty.tools.Color;

public class IngameController implements ScreenController{
	private GUI gui;
	private BuildObjectController buildObjectController;
	private Map map;
	private Screen ingameScreen;
	private IngameScreenHUD ingameScreenHUD;
	public Information info;

	private LinkedList<String> receiver;
	private int receiverToShow;

	private Element creepChoosed;
	private Element towerChoosed;
	private boolean ready=false;
	private ListBox<TextRenderer> chatBox;
	
	private LeaveGameScreen leaveGameScreen;
	private boolean start;
	private boolean towerTabClicked;
	private boolean showUpgradeOptions = false;
	private String myTile;
	private Tower towerToUpgrade;



	
	//Tile Option1 Variablen etc
	private Element tileChoosed;
	private Element tileSelected;
	private int tileNr;
	private Element readyPlayer;
	private boolean[] selectedTiles = new boolean[5];
	private boolean[] readyPlayers = new boolean[5];
	
	private int NumberOfPlayers;
	private boolean showTowerInformation;

	private boolean[] grayTower;
	private boolean[] grayCreep;
	private Element grayTowerChoosed;
	private Element grayCreepChoosed;
	private boolean gameOver;
//ENDE Tile Option1 Variablen etc
	
	
	
	
	
	
	public IngameController(GUI gui,IngameScreenHUD ingameScreenHUD) {
		this.gui =gui;
		buildObjectController=new BuildObjectController(gui, this);
		this.info=new Information(gui, this);
		this.ingameScreenHUD=ingameScreenHUD;
	}
	
	@SuppressWarnings("unchecked")
	public void bind(Nifty nifty, Screen ingameScreen) {
		this.ingameScreen=ingameScreen;
		this.map= gui.getIngameScreen().getIngameFunctions().getMap();
		chatBox = ingameScreen.findNiftyControl("chatBox", ListBox.class);
		receiver = new LinkedList<String>();
		receiver.add("");
//		this.ingameScreenHUD.initPopup();
		this.leaveGameScreen = new LeaveGameScreen(gui);
		LinkedList<String> strategies = new LinkedList<String>();
		strategies.add("Closest");
		strategies.add("Fastest");
		strategies.add("Strongest");
		strategies.add("Farthest");
		strategies.add("Weakest");
		ingameScreen.findNiftyControl("dropDown", DropDown.class).addAllItems(strategies);
		ingameScreen.findNiftyControl("dropDown Creep Panel", DropDown.class).addAllItems(strategies);
		grayTower = new boolean[6];
		grayCreep = new boolean[16];
	}
	
	public void showCreepSelection(){
		map.setModel_object(null);
		map.setModel_colored(null);
		map.setShowCells(false); //disable build area
		
		if(grayTowerChoosed != null) {
			grayTowerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			grayTowerChoosed = null;
			info.setValueTower(0, false);
		}
		
		if(towerChoosed != null) {
			towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			towerChoosed = null;
			info.setValueTower(0, false);
		}
		
		ingameScreen.findElementByName("TowerSelection").hide();
		ingameScreen.findElementByName("CreepSelection").show();
		towerTabClicked = false;
		if(!showUpgradeOptions) {
			ingameScreen.findElementByName("upgradePanel Creep Panel").hide();
		} 
		if(showTowerInformation) {
			ingameScreen.findElementByName("Creep Information").hide();
		} else {
			ingameScreen.findElementByName("Tower Information Creep Panel").hide();
		}
		if(!start) {
			ingameScreen.findElementByName("Creep Information").hide();
			hideTiles();
		} else {
			ingameScreen.findElementByName("Tile Selection Creep Panel").hide();
		}
		if(gameOver) {
			ingameScreen.findElementByName("Creep Information").hide();
			hideTiles();
			ingameScreen.findElementByName("upgradePanel Creep Panel").hide();
			ingameScreen.findElementByName("Tower Information Creep Panel").hide();
		} else {
			ingameScreen.findElementByName("Winner Panel Creep Panel").hide();
		}
		ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
	}
	
	public void showTowerSelection(){
		ingameScreen.findElementByName("CreepSelection").hide();
		ingameScreen.findElementByName("TowerSelection").show();
		towerTabClicked = true;
		ObjectPath.selectedCreep(-1);
		
		if(grayCreepChoosed != null) {
			grayCreepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			grayCreepChoosed = null;
			info.setValueCreep(0, false);
		}
		
		if(creepChoosed != null) {
			creepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			creepChoosed = null;
			info.setValueCreep(0, false);
		}
		
		if(!showUpgradeOptions) {
			ingameScreen.findElementByName("upgradePanel").hide();
		}
		if(!start) {
			ingameScreen.findElementByName("Tower Information").hide();
			hideTiles();
		} else {
			ingameScreen.findElementByName("Tile Selection Tower Panel").hide();
		}
		if(gameOver) {
			ingameScreen.findElementByName("Tower Information").hide();
			hideTiles();
			ingameScreen.findElementByName("upgradePanel").hide();
		} else {
			ingameScreen.findElementByName("Winner Panel").hide();
		}
	}
	
	public void creepclick(String creepNum){
		this.towerToUpgrade = null;
		showUpgradeOptions = false;
		showTowerInformation = false;
		
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}

		if(grayCreep[Integer.parseInt(creepNum)]) {
			if(grayCreepChoosed == null) {
				grayCreepChoosed = ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1));
				grayCreepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,0,1,1));
				info.setValueCreep(Integer.parseInt(creepNum),true);
			} else {
				if(grayCreepChoosed.getId().equals("creep"+(Integer.parseInt(creepNum)+1))) {
					grayCreepChoosed = null;
					ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1)).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					info.setValueCreep(0, false);
				} else {
					grayCreepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					grayCreepChoosed = ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1));
					grayCreepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,0,1,1));
					info.setValueCreep(Integer.parseInt(creepNum),true);
				}
			}
			
			if(creepChoosed != null) {
				creepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
				creepChoosed = null;
			}
			
			ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
			ObjectPath.selectedCreep(-1);
		} else {
			if(creepChoosed == null) {
				ObjectPath.selectedCreep(Integer.parseInt(creepNum));
				creepChoosed = ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1));
				creepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,1));
				info.setValueCreep(Integer.parseInt(creepNum),true);
				ingameScreen.findNiftyControl("recruitButton", Button.class).enable();
			} else {
				if(creepChoosed.getId().equals("creep"+(Integer.parseInt(creepNum)+1))) {
					ObjectPath.selectedCreep(-1);
					creepChoosed = null;
					ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1)).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					info.setValueCreep(0, false);
					ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
				} else {
					ObjectPath.selectedCreep(Integer.parseInt(creepNum));
					creepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					creepChoosed = ingameScreen.findElementByName("creep"+(Integer.parseInt(creepNum)+1));
					creepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,1));
					info.setValueCreep(Integer.parseInt(creepNum),true);
					ingameScreen.findNiftyControl("recruitButton", Button.class).enable();
				}
			}
			
			if(grayCreepChoosed != null) {
				grayCreepChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
				grayCreepChoosed = null;
			}
		}
	}
	
	public void towerClick(String towerNum){
		this.towerToUpgrade = null;
		showUpgradeOptions = false;
		showTowerInformation = false;
		
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}
		
		if(grayTower[Integer.parseInt(towerNum)]) {
			if(grayTowerChoosed == null) {
				grayTowerChoosed = ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1));
				grayTowerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,0,1,1));
				info.setValueTower(Integer.parseInt(towerNum),true);
			} else {
				if(grayTowerChoosed.getId().equals("tower"+(Integer.parseInt(towerNum)+1))) {
					grayTowerChoosed = null;
					ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1)).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					info.setValueTower(0, false);
				} else {
					grayTowerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					grayTowerChoosed = ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1));
					grayTowerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,0,1,1));
					info.setValueTower(Integer.parseInt(towerNum),true);
				}
			}
			
			if(towerChoosed != null) {
				towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
				towerChoosed = null;
			}
			
			map.setModel_object(null);
			map.setModel_colored(null);
			map.setTowerChoosed(false);
		} else {
			if(towerChoosed == null) {
				map.setShowCells(true); //show build area
				towerChoosed = ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1));
				towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,1));
				info.setValueTower(Integer.parseInt(towerNum),true);
				map.setModel_object(ObjectPath.get_Tower_Object_obj(Integer.parseInt(towerNum)));
				map.setModel_colored(ObjectPath.get_Tower_Object_colored(Integer.parseInt(towerNum)));
				map.setTowerChoosed(true);
			} else {
				if(towerChoosed.getId().equals("tower"+(Integer.parseInt(towerNum)+1))) {
					towerChoosed = null;
					ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1)).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					info.setValueTower(0, false);
					map.setModel_object(null);
					map.setModel_colored(null);
					map.setTowerChoosed(false);
				} else {
					towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
					towerChoosed = ingameScreen.findElementByName("tower"+(Integer.parseInt(towerNum)+1));
					towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,1));
					info.setValueTower(Integer.parseInt(towerNum),true);
					map.setModel_object(ObjectPath.get_Tower_Object_obj(Integer.parseInt(towerNum)));
					map.setModel_colored(ObjectPath.get_Tower_Object_colored(Integer.parseInt(towerNum)));
				}
			}	
			
			if(grayTowerChoosed != null) {
				grayTowerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
				grayTowerChoosed = null;
			}
		}
	}
	
	public void sendMessageIngame() {
		TextField textField = ingameScreen.findNiftyControl("chatMessagesField", TextField.class);
		String line = textField.getText();
		textField.setText("");
		
		if (line.startsWith("@SE") || line.startsWith("@Other")
				|| line.startsWith("@Team-")) {
			String[] split = line.split(" ");
			String receiver = split[0].substring(1);
			if (this.receiver.contains("@" + receiver + " ")) {
				this.receiver.remove("@" + receiver + " ");
			}
			this.receiver.add(this.receiver.size() - 1, "@" + receiver + " ");
			receiverToShow = this.receiver.size() - 1;
			String message = "";
			for (int i = 1; i < split.length; i++) {
				message += split[i] + " ";
			}
			if(split.length >= 2) {
				JsonSender.chatWithTeam(message, split[0].substring(1));
			}
		} else if(line.startsWith("@")) {
			String[] split = line.split(" ");
			String receiver = split[0].substring(1);
			String message = "";
			
			if (this.receiver.contains("@" + receiver + " ")) {
				this.receiver.remove("@" + receiver + " ");
			}
			this.receiver.add(this.receiver.size() - 1, "@" + receiver + " ");
			receiverToShow = this.receiver.size() - 1;
			
			for (int i = 1; i < split.length; i++) {
				message += split[i] + " ";
			}
			if(split.length >= 2) {
				JsonSender.chatWithUser(message, split[0].substring(1));
				
				boolean online = false;
				for (User user : gui.getStart().getLogic().getManager().getUsers().values()) {	
					if (user.getUserAssets() != null) {
						if (user.getNickname() != null) {
							if (user.getNickname().equals(split[0].substring(1))) {
								online = true;
							}
						}	
					}				
				}

				if (online) {
					gui.getIngameScreen().getIngameScreenHUD().getChatManager()
						.displayMessage(gui.getStart().getModel().getPlayerName(), split[0].substring(1), message, ChatManager.PRIVATE);
				}
			}
		} else {
			JsonSender.chatWithAll(line);
		}
		
	}
	

	
	@Override
	public void onEndScreen() {
		disableRed("TOP_LEFT");
		disableRed("TOP_RIGHT");
		disableRed("BOTTOM_LEFT");
		disableRed("BOTTOM_RIGHT");
		ingameScreenHUD.getChatManager().setUpperLeftPlayer("", "", 0);
		ingameScreenHUD.getChatManager().setUpperRightPlayer("", "", 0);
		ingameScreenHUD.getChatManager().setLowerLeftPlayer("", "", 0);
		ingameScreenHUD.getChatManager().setLowerRightPlayer("", "", 0);
		
		NOOP.stop();

		BackgroundMusic.get().startFadingOut();
	}
	
	@Override
	public void onStartScreen() {
		if(leaveGameScreen.isShowing()) {
			leaveGameScreen.closePopup();
		}

		if(!ingameScreenHUD.getChatManager().isShowingChatbox()) {
			ingameScreenHUD.getChatManager().toggleShow();
		}

		ingameScreen.findElementByName("towersButton").setFocus();
		
		chatBox.setListBoxViewConverter(new ChatListBoxViewConverter());
		addKeyboardListenerTo("chatMessagesField");
		ingameScreen.findElementByName("Creep Information").hide();
		ingameScreen.findElementByName("Tower Information").hide();
		map.setModel_object(null);
		map.setModel_colored(null);
		info.setValueCreep(0,false);
		info.setValueCreep(0, false);
		map.setTowerChoosed(false);
		towerTabClicked = true;
		start = false;
		gameOver = false;
		showTowerSelection();
		
		for(int i=1; i<=16; i++){
			ingameScreen.findElementByName("creep"+i).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			ingameScreen.findElementByName("creep"+i+"Image").enable();
		}
		creepChoosed = null;
		grayCreepChoosed = null;
		
		for(int i=1; i<=6;i++){
			ingameScreen.findElementByName("tower"+i).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			ingameScreen.findElementByName("tower"+i+"Image").enable();
		}
		towerChoosed = null;
		grayTowerChoosed = null;
		this.towerToUpgrade = null;
		showUpgradeOptions = false;
		showTowerInformation = false;
		ingameScreen.findNiftyControl("startButtonCreep", Button.class).disable();
		ingameScreen.findNiftyControl("startButtonTower", Button.class).disable();
		updateTiles();
		hideTiles();
		gui.getIngameScreen().getIngameFunctions().getMap().init();
	}
	
	private void updateTiles() {
		boolean allTilesSelected = true;
		for(Tile t: gui.getStart().getLogic().getManager().getTiles().values()) {
			if(t.getUserAssets() != null && t.getUserAssets().getUser() != null) {
				ingameScreenHUD.getController().enableRed(t.getPosition());
			} else {
				allTilesSelected = false;
				ingameScreenHUD.getController().disableRed(t.getPosition());
			}
		}
		
		if(allTilesSelected) {
			ingameScreenHUD.getController().getIngameScreen().findNiftyControl("startButtonTower", Button.class).enable();
			ingameScreenHUD.getController().getIngameScreen().findNiftyControl("startButtonCreep", Button.class).enable();
		}
	}

	private void hideTiles() {
		int tileNr = gui.getStart().getLogic().getGame().getNumPlayers();;
		
		if(tileNr == 1) {
			ingameScreen.findElementByName("tile" + 2 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 2 + "outer" + "Creep").hide();
			ingameScreen.findElementByName("tile" + 3 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 3 + "outer" + "Creep").hide();
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Creep").hide();
		} else if(tileNr == 2) {
			ingameScreen.findElementByName("tile" + 3 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 3 + "outer" + "Creep").hide();
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Creep").hide();
		} else if(tileNr == 3) {
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Tower").hide();
			ingameScreen.findElementByName("tile" + 4 + "outer" + "Creep").hide();
		} 

	}

	private void addKeyboardListenerTo(String elementName) {
		ingameScreen.findElementByName(elementName).addInputHandler(
				new KeyInputHandler() {
					@Override
					public boolean keyEvent(NiftyInputEvent inputEvent) {
						if (inputEvent == null)
							return false;
						switch (inputEvent) {
						case SubmitText:
							sendMessageIngame();
							return true;
						case MoveCursorUp:
							showPrevReceiver();
							return true;
						case MoveCursorDown:
							showNextReceiver();
							return true;
						default:
							break;
						}
						return false;
					}
				});

	}
	
	private void showNextReceiver() {
		TextField textField = ingameScreen.findNiftyControl("chatMessagesField",
				TextField.class);

		if (this.receiver.size() > 1) {
			receiverToShow++;
			if (receiverToShow >= this.receiver.size()) {
				receiverToShow = this.receiver.size() - 1;
			}
			String receiver = this.receiver.get(receiverToShow);
			textField.setText(receiver);
			textField.setCursorPosition(textField.getText().length());
		}
	}

	private void showPrevReceiver() {
		TextField textField = ingameScreen.findNiftyControl("chatMessagesField",
				TextField.class);

		if (this.receiver.size() > 1) {
			receiverToShow--;
			if (receiverToShow < 0) {
				receiverToShow = 0;
			}
			String receiver = this.receiver.get(receiverToShow);
			textField.setText(receiver);
			textField.setCursorPosition(textField.getText().length());
		}
	}
	
	public void recruit(){	
		buildObjectController.recruit();
	}
	
	public void addMessageToChatBox(String message, Color color) {
		TextBreak newMessage = new TextBreak(message, chatBox.getWidth() - 25,
				gui.getNifty().getRenderEngine().getFont());
		List<String> text = newMessage.split();
		List<TextRenderer> coloredText = new ArrayList<TextRenderer>();
		for (String s : text) {
			coloredText.add(new TextRenderer(gui.getNifty(), gui.getNifty().getRenderEngine()
					.getFont(), s));
		}
		for (TextRenderer t : coloredText) {
			t.setColor(color);
		}
		chatBox.addAllItems(coloredText);
		
		if(chatBox.getItems().size() > 200) {
			chatBox.removeItemByIndex(0);
		}

		chatBox.showItemByIndex(chatBox.getItems().size() - 1);
	}
	
	public void tileClick(String tile) {
		
		String forTesting = "";
		switch (Integer.parseInt(tile.charAt(4) + "")) {
		
		case 1: forTesting = "TOP_LEFT"; break;
		case 2: forTesting = "TOP_RIGHT"; break;
		case 3: forTesting = "BOTTOM_RIGHT"; break;
		case 4: forTesting = "BOTTOM_LEFT"; break;
		
		}
		
		myTile = forTesting;
		
		for(Tile t : gui.getStart().getLogic().getManager().getTiles().values()) {
			if(t.getPosition().equals(forTesting)) {
				JsonSender.chooseTile(t.getID());
				break;
			}
		}
	}	
	
	public void startButtonclick() {
		JsonSender.startGame();
		startGame();
	}
	
	public void startGame() {
		hideAndShowAfterTileSelection();
		if(creepChoosed != null) {
			ingameScreen.findNiftyControl("recruitButton", Button.class).enable();
		}
	}

	public void hideAndShowAfterTileSelection() {
		start = true;
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}
	}
	
	public LeaveGameScreen getLeaveGameScreen() {
		return leaveGameScreen;
	}
	
	public void leaveGame() {
		clear();
		EffectManager.get().clear();
		JsonSender.leaveGame();
		gui.setFollowingScreen(gui.getLobbyScreen());
		gui.getStart().getConnection().setMessageReceiver(new ConnectionHandler(gui.getStart()));
		gui.getStart().getConnection().sendMessage("LIST MAPS");
		gui.getStart().getLogic().getManager().clearDataModel();
	}
	
	public void closeExitGamePopup() {
		leaveGameScreen.closePopup();
	}
	
	private void clear() {
		chatBox.clear();
	}

	public void disableRed(String tile) {
		int tileNr = getTileNr(tile);
		
		Element elem = ingameScreen.findElementByName("tile" + tileNr + "outer" + "Tower");
		elem.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,1,1,0.66f));
		elem.enable();
		elem = ingameScreen.findElementByName("tile" + tileNr + "outer" + "Creep");
		elem.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,1,1,0.66f));
		elem.enable();
	}


	public void enableRed(String tile) {
		int tileNr = getTileNr(tile);
		
		Element elem = ingameScreen.findElementByName("tile" + tileNr + "outer" + "Tower");
		elem.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,0.8f));
		elem.disable();
		elem = ingameScreen.findElementByName("tile" + tileNr + "outer" + "Creep");
		elem.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,0.8f));
		elem.disable();
	}
	
	private int getTileNr(String tile) {
		int tileNr = 0;
		if("TOP_LEFT".equals(tile)) {
			tileNr = 1;
		} else if("TOP_RIGHT".equals(tile)) {
			tileNr = 2;
		} else if("BOTTOM_RIGHT".equals(tile)) {
			tileNr = 3;
		} else {
			tileNr = 4;
		}
		return tileNr;
	}
	
	public Screen getIngameScreen() {
		return ingameScreen;
	}
	
	@NiftyEventSubscriber(pattern="name_.*")
	public void clickedOnName(String id, NiftyMousePrimaryClickedEvent event) {
		String receiver = ingameScreen.findNiftyControl(id, Label.class).getText();
		
		setReceiver(receiver);
	}
	
	@NiftyEventSubscriber(pattern="team_.*")
	public void clickedOnTeam(String id, NiftyMousePrimaryClickedEvent event) {
		String receiver = ingameScreen.findNiftyControl(id, Label.class).getText();
		receiver = receiver.substring(1, receiver.length() - 1);
		
		setReceiver(receiver);
	}
	
	@NiftyEventSubscriber(pattern="dropDown*")
	public void onDropDownSelectionChanged(String id, DropDownSelectionChangedEvent<String> event) {
		if(showUpgradeOptions) {  
			String strategy = event.getSelection();
			String tower = towerToUpgrade.getID();
			JsonSender.changeTowerStrategy(tower, strategy.toUpperCase());
		}
	}
	
	private void setReceiver(String receiver) {
		TextField t = ingameScreen.findNiftyControl("chatMessagesField", TextField.class);
		TextField t1 = ingameScreen.findNiftyControl("chatMessagesFieldTileSelection", TextField.class);
		String text = t.getText();
		if(text != null) {
			if(text.startsWith("@")) {
				String[] split = text.split(" ");
				text = "@" + receiver;
				for(int i = 1; i < split.length; i++) {
					text += " " + split[i];
				}
			} else {
				text = "@" + receiver + " " + text;
			}
		} else {
			text = "@" + receiver + " ";
		}
		
		t.setText(text + " ");
		t1.setText(text + " ");
		t.getElement().setFocus();
		t1.getElement().setFocus();
		t.setCursorPosition(text.length());
		t.setFocus();
		t.setCursorPosition(t.getText().length());
		t1.setFocus();
		t1.setCursorPosition(t.getText().length());
	}
	
	public String getMyTile() {
		return myTile;
	}
	
	
	//TileSelection Option1
	
	public void initNumberOfPlayers(){
		 for (int i=1; i<=4 ; i++){
		       ingameScreen.findElementByName("listpanelPlayer"+i).hide();
			 }
		 for (int i=1; i<=4 ; i++){
			   ingameScreen.findElementByName("tile"+i+"outer").hide();
		 }
		NumberOfPlayers=gui.getStart().getLogic().getGame().getNumPlayers();
		 for (int i=1; i<=NumberOfPlayers ; i++){
	       ingameScreen.findElementByName("listpanelPlayer"+i).show();
		 }
		 for (int i=1; i<=NumberOfPlayers ; i++){
		       ingameScreen.findElementByName("tile"+i+"outer").show();
			 }
	}
	
	
	public void initReadyPlayers(){
		readyPlayers[1]=false;//true--> player hat bereits ready gedrueckt
		readyPlayers[2]=false;
		readyPlayers[3]=false;
		readyPlayers[4]=false;
		updateReadyPlayers();
	}
	public void updateReadyPlayers(){
		String readyValuePlayerName;
    for (int i=1; i<=NumberOfPlayers ; i++){
     	if(readyPlayers[i]==true){
     		readyValuePlayerName="readyValuePlayer"+(i);
     		readyPlayer=ingameScreen.findElementByName(readyValuePlayerName);
     		readyPlayer.getRenderer(TextRenderer.class).setText("ready");
     		readyPlayer.getRenderer(TextRenderer.class).setColor(new Color(0,1,0,1f));
	    }
    }
	}
	
	public void initSelectedTiles(){
		selectedTiles[1]=false;//true--> feld bereits belegt
		selectedTiles[2]=false;
		selectedTiles[3]=false;
		selectedTiles[3]=false;
		updateSelectedTiles();
	}
	public void updateSelectedTiles(){
		String tileSelectedName;
    for (int i=1; i<=NumberOfPlayers ; i++){
     	if(selectedTiles[i]==true){
     		tileSelectedName="tile"+(i)+"outer";
     		tileSelected=ingameScreen.findElementByName(tileSelectedName);
     		tileSelected.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,0,0,0.8f));
	    }
    }
	}
	
	public void readyButtonclick(){
		if((tileChoosed != null)&&(selectedTiles[tileNr]==false)) {					
		selectedTiles[tileNr]=true;		
		readyPlayers[tileNr]=true;
		updateReadyPlayers();
		fillselectedTiles(getTileName(tileNr));		
		Boolean allFieldsChoosed=true;
		ready=true;
	    for (int i=1; i<=NumberOfPlayers ; i++){    	
	     	if(selectedTiles[i]==false){
	     		allFieldsChoosed=false;
		    }
	    } 		    	
	   if (allFieldsChoosed==true){
		   ingameScreen.findElementByName("startGameCountdownPanel").show();
		   ingameScreen.findElementByName("waitingForOtherPlayers").hide();
		   ingameScreen.findElementByName("noTileChoosedPanel").hide();
		   //startGameCountdown();
	   }else{
		   ingameScreen.findElementByName("waitingForOtherPlayers").show();
		   ingameScreen.findElementByName("startGameCountdownPanel").hide();
		   ingameScreen.findElementByName("noTileChoosedPanel").hide();
	   }
	   }else{
			ingameScreen.findElementByName("noTileChoosedPanel").show();
			ingameScreen.findElementByName("startGameCountdownPanel").hide();
			ingameScreen.findElementByName("waitingForOtherPlayers").hide();
		}
	}
	public String getTileName(int tileNr){
	String tilename = "";
	switch (tileNr) {
	
	case 1: tilename = "TOP_LEFT"; break;
	case 2: tilename = "TOP_RIGHT"; break;
	case 3: tilename = "BOTTOM_RIGHT"; break;
	case 4: tilename = "BOTTOM_LEFT"; break;
	
	}
	
	return tilename;
	}
	
	public void tileClick1(String tile){
		boolean selected = false;
		tileNr = tile.charAt(4)-48;
		if(ready==false){
			if(selectedTiles[tileNr] == true) {
				selected = true;
			}
			if(selected == false) {	
				if(tileChoosed == null) {
					tileChoosed = ingameScreen.findElementByName(tile+"outer");
					tileChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,1,0,0.8f));	
				} else {
					if(tileChoosed.getId().equals(tile+"outer")) {
						tileChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,1,1,0.66f));
						tileChoosed = null;
					} else {
						tileChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(1,1,1,0.66f));
						tileChoosed = ingameScreen.findElementByName(tile+"outer");
						tileChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0,1,0,0.8f));
					}
				}
			}
		}	
	}	
	
	public void fillselectedTiles(String tilename) {
	int tileNr =getTileNr(tilename);		
		for(Tile t : gui.getStart().getLogic().getManager().getTiles().values()) {
			if(t.getPosition().equals(tilename)) {
				JsonSender.chooseTile(t.getID());
				selectedTiles[tileNr]=true;
				readyPlayers[tileNr]=true;
				updateSelectedTiles();
				updateReadyPlayers();
				break;
			}
		}
	}	
	public void defillselectedTiles(String tilename) {
		int tileNr =getTileNr(tilename);
		updateSelectedTiles();
        selectedTiles[tileNr]=false;
		}	
	
	public void tileChooseOption1Prefences(){
		ingameScreen.findElementByName("controlPanel").hide();
		ingameScreen.findElementByName("tileSelection").show();
		initNumberOfPlayers();
		initSelectedTiles();
		initReadyPlayers();
	}
	public Information getInfo() {
		return info;
	}

	public void updateGold(String gold) {
		Element goldvalue = ingameScreen.findElementByName("GoldValue");
		goldvalue.getRenderer(TextRenderer.class).setText(gold);
		for (TowerDescription t : gui.getStart().getLogic().getManager()
				.getTowerDescriptions().values()) {
			if (t.getLevel() == 1) {
				String[] towernames = { "Basic", "Slow", "Splash", "Rocket",
						"Speed", "Ultimate" };
				for (int i = 0; i < towernames.length; i++) {
					if (t.getType().equalsIgnoreCase(towernames[i])) {
						Element outer = ingameScreen.findElementByName("tower"
								+ (i + 1));
						Element image = ingameScreen.findElementByName("tower"
								+ (i + 1) + "Image");
						if (t.getPrice() > Integer.parseInt(gold)) {
							NiftyImage img = gui
									.getNifty()
									.getRenderEngine()
									.createImage(
											"res/img/ingameControlbar/tower"
													+ (i + 1) + "_gray.png",
											false);
							grayTower[i] = true;
							image.getRenderer(ImageRenderer.class)
									.setImage(img);

							if (towerChoosed != null
									&& towerChoosed.getId().equals(
											outer.getId())) {
								towerChoosed.getRenderer(PanelRenderer.class)
										.setBackgroundColor(
												new Color(0, 0, 1, 1));
								grayTowerChoosed = towerChoosed;
								towerChoosed = null;
								map.setShowCells(false); // show build area
								map.setModel_object(null);
								map.setModel_colored(null);
								map.setTowerChoosed(false);
							}
						} else {
							NiftyImage img = gui
									.getNifty()
									.getRenderEngine()
									.createImage(
											"res/img/ingameControlbar/tower"
													+ (i + 1) + ".png", false);
							grayTower[i] = false;
							image.getRenderer(ImageRenderer.class)
									.setImage(img);

							if (grayTowerChoosed != null
									&& grayTowerChoosed.getId().equals(
											outer.getId())) {
								grayTowerChoosed.getRenderer(
										PanelRenderer.class)
										.setBackgroundColor(
												new Color(1, 0, 0, 1));
								towerChoosed = grayTowerChoosed;
								grayTowerChoosed = null;
								map.setShowCells(true); // show build area
								map.setModel_object(ObjectPath
										.get_Tower_Object_obj(i));
								map.setModel_colored(ObjectPath
										.get_Tower_Object_colored(i));
								map.setTowerChoosed(true);
							}
						}
					}
				}
			}
		}
		for (CreepDescription c : gui.getStart().getLogic().getManager()
				.getCreepDescriptions().values()) {
			String[] creepnames = { "Mercury", "Mako", "FastNova",
					"LargeManta", "Demeter", "Ray", "SpeedyRaider",
					"BigToucan", "Vulture", "Shark", "RacingMamba",
					"HugeTitan", "Zeus", "Phoenix", "ExpressRaptor",
					"FatColossus" };
			for (int i = 0; i < creepnames.length; i++) {
				if (c.getType().equalsIgnoreCase(creepnames[i])) {
					Element outer = ingameScreen.findElementByName("creep"
							+ (i + 1));
					Element image = ingameScreen.findElementByName("creep"
							+ (i + 1) + "Image");
					if (c.getPrice() > Integer.parseInt(gold)) {
						NiftyImage img = gui
								.getNifty()
								.getRenderEngine()
								.createImage(
										"res/img/ingameControlbar/creep"
												+ (i + 1) + "_gray.png", false);
						grayCreep[i] = true;
						image.getRenderer(ImageRenderer.class).setImage(img);

						if (creepChoosed != null
								&& creepChoosed.getId().equals(outer.getId())) {
							creepChoosed.getRenderer(PanelRenderer.class)
									.setBackgroundColor(new Color(0, 0, 1, 1));
							grayCreepChoosed = creepChoosed;
							creepChoosed = null;
							ObjectPath.selectedCreep(-1);
							ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
						}
					} else {
						NiftyImage img = gui
								.getNifty()
								.getRenderEngine()
								.createImage(
										"res/img/ingameControlbar/creep"
												+ (i + 1) + ".png", false);
						grayCreep[i] = false;
						image.getRenderer(ImageRenderer.class).setImage(img);

						if (grayCreepChoosed != null
								&& grayCreepChoosed.getId().equals(
										outer.getId())) {
							grayCreepChoosed.getRenderer(PanelRenderer.class)
									.setBackgroundColor(new Color(1, 0, 0, 1));
							creepChoosed = grayCreepChoosed;
							grayCreepChoosed = null;
							ObjectPath.selectedCreep(i);
							ingameScreen.findNiftyControl("recruitButton", Button.class).enable();
						}
					}
				}
			}
		}

		if (showUpgradeOptions
				&& (!ingameScreen.findElementByName("PriceTowerValue")
						.getRenderer(TextRenderer.class).getOriginalText()
						.contains("(")
				|| Integer.parseInt(ingameScreen
						.findElementByName("PriceTowerValue")
						.getRenderer(TextRenderer.class).getOriginalText()
						.split("\\(")[1].split("\\)")[0]) > Integer
						.parseInt(gold))) {
			ingameScreen.findNiftyControl("upgradeButton", Button.class)
					.disable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel",
					Button.class).disable();
		} else {
			ingameScreen.findNiftyControl("upgradeButton", Button.class)
					.enable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel",
					Button.class).enable();
		}
	}

	public void updateLives(String lives) {
		Element livesValue = ingameScreen.findElementByName("LifeValue");
		livesValue.getRenderer(TextRenderer.class).setText(lives);
		if(Integer.parseInt(lives) <= 0) {
			setGameOverWindow("You Loose!");
		}
	}

	private void setGameOverWindow(String text) {
		gameOver = true;
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}
		towerChoosed = null;
		map.setShowCells(false);
		map.setModel_object(null);
		map.setModel_colored(null);
		map.setTowerChoosed(false);
		grayTowerChoosed = null;
		creepChoosed = null;
		grayCreepChoosed = null;
		for(int i=1; i<=16; i++){
			ingameScreen.findElementByName("creep"+i).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			ingameScreen.findElementByName("creep"+i+"Image").getRenderer(ImageRenderer.class).setImage(gui.getNifty().createImage("res/img/ingameControlbar/creep"	+ i + "_gray.png", false));
			ingameScreen.findElementByName("creep"+i+"Image").disable();
		}
		for(int i=1; i<=6;i++){
			ingameScreen.findElementByName("tower"+i).getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			ingameScreen.findElementByName("tower"+i+"Image").getRenderer(ImageRenderer.class).setImage(gui.getNifty().createImage("res/img/ingameControlbar/tower"	+ i + "_gray.png", false));
			ingameScreen.findElementByName("tower"+i+"Image").disable();
		}
		ingameScreen.findElementByName("Winner/Loser Text").getRenderer(TextRenderer.class).setText(text);
		ingameScreen.findElementByName("Winner/Loser Text Creep Panel").getRenderer(TextRenderer.class).setText(text);
	}

	public void sellTower() {
		String tower = towerToUpgrade.getID();
		ingameScreen.findNiftyControl("sellButton", Button.class).disable();
		ingameScreen.findNiftyControl("sellButton Creep Panel", Button.class)
				.disable();
		ingameScreen.findNiftyControl("upgradeButton", Button.class).disable();
		ingameScreen
				.findNiftyControl("upgradeButton Creep Panel", Button.class)
				.disable();
		ingameScreen.findNiftyControl("dropDown", DropDown.class).disable();
		ingameScreen.findNiftyControl("dropDown Creep Panel", DropDown.class)
				.disable();
		JsonSender.sellTower(tower);
	}

	public void upgradeTower() {
		String tower = towerToUpgrade.getID();
		int level = towerToUpgrade.getLevel();
		
		if (towerToUpgrade.getType().equals("Ultimate")) {
			if (level == 1) {
				JsonSender.upgradeTower(tower, (level + 1) + "");
				ingameScreen.findNiftyControl("upgradeButton", Button.class)
						.disable();
				ingameScreen.findNiftyControl("upgradeButton Creep Panel",
						Button.class).disable();
			}
		} else {
			if (level < 4) {
				JsonSender.upgradeTower(tower, (level + 1) + "");
				ingameScreen.findNiftyControl("upgradeButton", Button.class)
						.disable();
				ingameScreen.findNiftyControl("upgradeButton Creep Panel",
						Button.class).disable();
			}
		}
	}
	

	
	public Element getCreepChoosed() {
		return creepChoosed;
	}
	public Element getTowerChoosed() {
		return towerChoosed;
	}

	public void setTowerChoosed(Element towerChoosed) {
		if(towerChoosed == null) {
			this.towerChoosed.getRenderer(PanelRenderer.class).setBackgroundColor(new Color(0, 0, 0, 0));
			info.setValueTower(0, false);
		}
		this.towerChoosed = towerChoosed;
	}
	
	public void disableTowerUpgradeWindow() {
		this.towerToUpgrade = null;
		showUpgradeOptions = false;
		showTowerInformation = false;
		if(grayTowerChoosed != null) {
			grayTowerChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			grayTowerChoosed = null;
		}
		if(grayCreepChoosed != null) {
			grayCreepChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			grayCreepChoosed = null;
			ObjectPath.selectedCreep(-1);
			info.setValueCreep(0, false);
		}
		if(creepChoosed != null) {
			creepChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
			creepChoosed = null;
			ObjectPath.selectedCreep(-1);
			info.setValueCreep(0, false);
		}
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}
		info.setValueTower(0, false);
	}

	public void enableTowerUpgradeWindow(Tower tower, String tile) {
		this.towerToUpgrade = tower;
		showTowerInformation = true;
		if(grayTowerChoosed != null) {
			grayTowerChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			grayTowerChoosed = null;
		}
		if(grayCreepChoosed != null) {
			grayCreepChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			grayCreepChoosed = null;
			ObjectPath.selectedCreep(-1);
			info.setValueCreep(0, false);
		}
		if(creepChoosed != null) {
			ObjectPath.selectedCreep(-1);
			info.setValueCreep(0, false);
			ingameScreen.findNiftyControl("recruitButton", Button.class).disable();
			creepChoosed.getRenderer(
					PanelRenderer.class)
					.setBackgroundColor(
							new Color(0, 0, 0, 0));
			creepChoosed = null;
		}
		if(tile.equals(myTile)) {
			showUpgradeOptions = true;
		} else {
			showUpgradeOptions = false;
		}
		
		if(towerTabClicked) {
			showTowerSelection();
		} else {
			showCreepSelection();
		}
		
		if(tower.isUpgrading()) {
			ingameScreen.findNiftyControl("upgradeButton", Button.class).disable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel", Button.class).disable();
		} else {
			ingameScreen.findNiftyControl("upgradeButton", Button.class).enable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel", Button.class).enable();
		}
		
		if(tower.isSelling()) {
			ingameScreen.findNiftyControl("sellButton", Button.class).disable();
			ingameScreen.findNiftyControl("sellButton Creep Panel", Button.class).disable();
			ingameScreen.findNiftyControl("upgradeButton", Button.class).disable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel", Button.class).disable();
			ingameScreen.findNiftyControl("dropDown", DropDown.class).disable();
			ingameScreen.findNiftyControl("dropDown Creep Panel", DropDown.class).disable();
		} else {
			ingameScreen.findNiftyControl("sellButton", Button.class).enable();
			ingameScreen.findNiftyControl("sellButton Creep Panel", Button.class).enable();
			ingameScreen.findNiftyControl("upgradeButton", Button.class).enable();
			ingameScreen.findNiftyControl("upgradeButton Creep Panel", Button.class).enable();
			ingameScreen.findNiftyControl("dropDown", DropDown.class).enable();
			ingameScreen.findNiftyControl("dropDown Creep Panel", DropDown.class).enable();
		}
		
		info.setValueForTowerUpgrade(tower);
	}

	public void updateTowerInfo(Tower tower) {
		if(towerToUpgrade != null && tower.getID().equals(towerToUpgrade.getID())) {
			enableTowerUpgradeWindow(tower, tower.getCell().getMap().getTile().getPosition());
		}
	}
	
	public Element getGrayTowerChoosed() {
		return grayTowerChoosed;
	}
	
	public Element getGrayCreepChoosed() {
		return grayCreepChoosed;
	}
	
	public boolean getGameOver() {
		return gameOver;
	}

	public void setLoserWinnerAnimationOnTile(String tile, String animationLetters) {
		int tileNr = getTileNr(tile);
		switch(tileNr) {
		case 1: 
			if(animationLetters.equals("Loser")) {
				map.setQ1(0.1f);
			}
			EffectManager.get().addEffect(new LetterAnimation(-0.5f, -0.5f, animationLetters));
			break;
		case 2:
			if(animationLetters.equals("Loser")) {
				map.setQ2(0.1f);
			}
			EffectManager.get().addEffect(new LetterAnimation(0.4f, -0.5f, animationLetters));
			break;
		case 3:
			if(animationLetters.equals("Loser")) {
				map.setQ4(0.1f);
			}
			EffectManager.get().addEffect(new LetterAnimation(0.4f, 0.5f, animationLetters));
			break;
		case 4:
			if(animationLetters.equals("Loser")) {
				map.setQ3(0.1f);
			};
			EffectManager.get().addEffect(new LetterAnimation(-0.5f, 0.5f, animationLetters));
			break;
		}
	}

	public void setWinner(String winnerTile) {
		if(winnerTile.equals(myTile)) {
			setGameOverWindow("You Win!");
		}
	}
	
	public Tower getTowerToUpgrade() {
		return towerToUpgrade;
	}
	
	public boolean getStart() {
		return start;
	}
}
